import { createSignal, onMount } from "solid-js";
import Button from "./Button";

type CountDownProps = {
  start: number;
  onDone?: () => void;
};

export default function CountDown({ start, onDone }: CountDownProps) {
  const [current, setCurrent] = createSignal(start);

  const countDown = () => {
    setCurrent(start);
    const i = setInterval(() => {
      const newCurrent = Math.max(current() - 1, 0);
      setCurrent(newCurrent);
      if (newCurrent <= 0) {
        clearInterval(i);
        onDone?.();
      }
    }, 1000);
  };

  onMount(() => {
    countDown();
  });

  return (
    <div>
      {current()}
      {current() <= 0 ? <Button onClick={countDown}>Reset</Button> : null}
    </div>
  );
}
